package com.baozhun.mall.common.network

import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.model.bean.ApiResponse
import com.baozhun.mall.common.util.CacheUtil
import com.baozhun.mall.common.util.Constants
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * 作者　: hegaojian
 * 时间　: 2022/1/13
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    private val gson: Gson by lazy { Gson() }

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        return if (response.body() != null && response.body()!!.contentType() != null) {
            val mediaType = response.body()!!.contentType()
            val string = response.body()!!.string()
            val responseBody = ResponseBody.create(mediaType, string)
            try {
                val apiResponse = gson.fromJson(string, ApiResponse::class.java)
                //token失效处理
                if (apiResponse.code == Constants.Common.TOKEN_INVALID) {
                    ToastUtils.showShort(apiResponse.msg)
                    CacheUtil.clearUserInfo()
                    ARouter.getInstance().build(RoutePath.Me.LOGIN).navigation()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}